package com.minglead.crawler.config;

import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.action.admin.cluster.settings.ClusterUpdateSettingsRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.settings.Settings;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;

@Configuration
public class ElasticsearchConfig {

    @Value("${elasticsearch.host}")
    private String esHost;
    @Value("${elasticsearch.port}")
    private int esPort;
    @Value("${elasticsearch.scheme}")
    private String esScheme;
    @Value("${elasticsearch.username}")
    private String username;
    @Value("${elasticsearch.password}")
    private String password;

    public final static String INDEX_NAME = "news";

    @Bean(name = "elasticsearchConfigYQ")
    public RestHighLevelClient restHighLevelClient() throws IOException {
        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        /** 设置账号密码 */
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(new HttpHost(esHost, esPort, esScheme))
                        .setHttpClientConfigCallback(httpClientBuilder -> {
                            // 设置连接和套接字超时
                            return httpClientBuilder
                                    .setDefaultCredentialsProvider(credentialsProvider)
                                    .setDefaultRequestConfig(RequestConfig.custom()
                                    .setConnectTimeout(1800000) // 连接超时时间，单位毫秒
                                    .setSocketTimeout(1800000) // 套接字超时时间，单位毫秒
                                    .build());
                        })
        );
        // 设置 max_buckets 的值
        Settings.Builder persistentSettings = Settings.builder().put("search.max_buckets", Integer.MAX_VALUE);
        // 更新集群设置
        client.cluster().putSettings(new ClusterUpdateSettingsRequest()
                        .persistentSettings(persistentSettings.build()), RequestOptions.DEFAULT);
        return client;
    }
}
